package com.candy.db.generator.utils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yantingjun on 2016/7/13.
 */
public class BeanToMap<K, V> {
    private BeanToMap() {
    }

    @SuppressWarnings("unchecked")
    public static <K, V> Map<K, V> Bean2Map(Object javaBean) {
        Map<K, V> ret = new HashMap<K, V>();
        try {
            Method[] methods = javaBean.getClass().getDeclaredMethods();
            for (Method method : methods) {
                if (method.getName().startsWith("get")) {
                    String field = method.getName();
                    field = field.substring(field.indexOf("get") + 3);
                    if ("class".equalsIgnoreCase(field)) {
                        continue;
                    }
                    field = field.toLowerCase().charAt(0) + field.substring(1);
                    Object value = method.invoke(javaBean, (Object[]) null);
                    ret.put((K) field, (V) (null == value ? "" : value));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
}